import re
import os
import sys
import string


def string_replace(lines, old, new):
    out = []
    for line in lines:
        out.append(re.sub(old, new, line))

    return out


def generate_cmake_option_file(file_output, file_input='.config'):
    lines = open(file_input, 'r', encoding='utf-8').readlines()
    lines = string_replace(lines, "^(CONFIG_[^=]+)=y", "option(\\1 \"\\1\")")
    lines = string_replace(
        lines, "^# (CONFIG_[^ ]+)[^\r\n]+", "# option(\\1 \"\\1\")")

    with open(file_output, 'w', encoding='utf-8') as f:
        f.write(
            '# cmake option file\n# this file create by tools automaic,please do not edit it.\n\n\n')
        f.writelines(lines)


def generate_header_file(file_output, file_input='.config'):
    lines = open(file_input, 'r', encoding='utf-8').readlines()
    lines = string_replace(lines, "^# (CONFIG_[^ ]+)[\W]+", "// #define \\1")
    lines = string_replace(lines, "^(CONFIG_[^=]+)=y", "#define \\1")

    with open(file_output, 'w', encoding='utf-8') as f:
        f.write('#ifndef __CONFIG_H__\n#define __CONFIG_H__\n\n\n')
        f.writelines(lines)
        f.write("\n#endif /*__CONFIG_H__*/\n")

if __name__ == "__main__":
    if len(sys.argv) > 2:

        print("%s %s" % (sys.argv[1], sys.argv[2]))

        generate_cmake_option_file(sys.argv[1]+'.cmake', sys.argv[2])
        generate_header_file(sys.argv[1]+'.h', sys.argv[2])
        print("config files generate complete")

# generate_cmake_option_file("config.cmake", ".config")
# generate_header_file("config.h", ".config")

# print("config files generate complete")